{% extends 'base/userinfo.html' %}


{% block head %}

<meta charset="utf-8">
<title>应用配置 管理界面</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/asset/layui/css/layui.css" media="all">
<link rel="stylesheet" href="/asset/css/global.css" media="all">
<script src="/asset/js/js-yaml.min.js"></script>
<script src="/asset/js/jsdifflib/difflib.js"></script>
<script src="/asset/js/jsdifflib/diffview.js"></script>
<link rel="stylesheet" href="/asset/js/jsdifflib/diffview.css" media="all">
<script src="/asset/js/util.js" charset="utf-8"></script>

<style>
    .layui-body {
        left: 30px !important;
    }

    .e {
        height: 600px;
        min-width: 1000px;
        font-size: 14px;
    }

    #diffoutput {
        height: 900px;
        width: 1460px;
        overflow: auto;
    }

</style>

{% endblock %}

{% block body %}

<div id="diff" style="display: none">
    <div id="diffoutput"></div>
</div>

<div id="box" style="display: none">
    <h1 class="site-h1"></h1>

    <form class="layui-form" action="" id="item-form">
        <input type="text" name="_id" id="_id" style="display: none">

        <div class="layui-form-item">
            <label class="layui-form-label">应用名称</label>

            <div class="layui-input-block">
                <input type="text" name="app_name" autocomplete="off" placeholder="" class="layui-input "
                       id="create_app_name">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">应用描述</label>

            <div class="layui-input-block">
                <input type="text" name="remark" autocomplete="off" placeholder="" class="layui-input  "
                >
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">tag</label>

            <div class="layui-input-block">
                <input type="text" name="tag" autocomplete="off" placeholder="" class="layui-input  "
                >
            </div>
        </div>

        
        <div class="layui-form-item">
            <div class="layui-input-block">
                {% if permission.template %}
                <button class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
                {% endif %}

            </div>
        </div>

    </form>

</div>


<div id="box_add_global_template" style="display: none">
    <h1 class="site-h1"></h1>

    <form class="layui-form" action="" id="form_add_global_template">

        <div class="layui-form-item">
            <label class="layui-form-label">应用名称</label>

            <div class="layui-input-block">
                <input type="text" name="app_name" autocomplete="off" placeholder="" class="layui-input "
                       id="add_global_template_app_name">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">模板名称</label>

            <div class="layui-input-block">
                <select name="global_template1" id="global_template" lay-filter="select_global_template">
                    <option value=""></option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">环境</label>

            <div class="layui-input-block">
                <a class="layui-btn btn_global_template" id="btn_global_template_dev">dev</a>
                <a class="layui-btn btn_global_template layui-btn-primary " id="btn_global_template_testenv">testenv</a>
                <a class="layui-btn btn_global_template layui-btn-primary " id="btn_global_template_prod">prod</a>
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">预设模板</label>

            <div class="layui-input-block">
                <div class="e" id="editor_add_global_template"></div>
                <script src="/asset/js/ace.js" type="text/javascript"
                        charset="utf-8"></script>

                <script>
                    var editor_add_global_template = ace.edit("editor_add_global_template");
                    editor_add_global_template.setTheme("ace/theme/monokai");
                    editor_add_global_template.getSession().setMode("ace/mode/yaml");

                    editor_add_global_template.container.style.lineHeight = 2
                    editor_add_global_template.container.style.fontSize = "14px"
                    editor_add_global_template.renderer.updateFontSize()
                </script>

            </div>


        </div>


        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="demo3" id="submit_add">立即提交</button>
                <button class="layui-btn layui-btn-danger" lay-submit="" lay-filter="demo4" id="submit_delete">删除
                </button>

            </div>
        </div>

    </form>

</div>


<div id="box_config" style="display: none">
    <h1 class="site-h1"></h1>

    <form class="layui-form" action="" id="item_form_config">

        <div class="layui-form-item">
            <label class="layui-form-label">应用名称</label>

            <div class="layui-input-block">
                <input type="text" name="app_name" autocomplete="off" placeholder="" class="layui-input  layui-disabled"
                       disabled>
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">环境</label>

            <div class="layui-input-block">
                <input type="text" name="env" autocomplete="off" placeholder="" class="layui-input  layui-disabled"
                       disabled>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">应用配置</label>

            <div class="layui-input-block">
                <div class="e" id="editor_config"></div>
                <script src="/asset/js/ace.js" type="text/javascript"
                        charset="utf-8"></script>

                <script>
                    var editor_config = ace.edit("editor_config");
                    editor_config.setTheme("ace/theme/monokai");
                    editor_config.getSession().setMode("ace/mode/yaml");

                    editor_config.container.style.lineHeight = 2
                    editor_config.container.style.fontSize = "14px"
                    editor_config.renderer.updateFontSize()
                </script>

            </div>


        </div>


        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="demo2">立即提交</button>
            </div>
        </div>

    </form>

</div>


<div id="box_display" style="display: none">
    <h1 class="site-h1"></h1>

    <form class="layui-form" action="" id="item_form_display">

        <div class="layui-form-item">
            <label class="layui-form-label">应用名称</label>

            <div class="layui-input-block">
                <input type="text" name="app_name" autocomplete="off" placeholder="" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">环境</label>

            <div class="layui-input-block">
                <input type="text" name="env" autocomplete="off" placeholder="" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">应用配置</label>

            <div class="layui-input-block">
                <div class="e" id="editor_display"></div>
                <script src="/asset/js/ace.js" type="text/javascript"
                        charset="utf-8"></script>

                <script>
                    var editor_display = ace.edit("editor_display");
                    editor_display.setTheme("ace/theme/monokai");
                    editor_display.getSession().setMode("ace/mode/yaml");

                    editor_display.container.style.lineHeight = 2
                    editor_display.container.style.fontSize = "14px"
                    editor_display.renderer.updateFontSize()
                </script>

            </div>


        </div>


        <div class="layui-form-item">
            <div class="layui-input-block">
            </div>
        </div>

    </form>

</div>


<div class="layui-body">

    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
            <li class="layui-this"><a href="index2.html">应用配置</a></li>
            <li><a href="index.html">环境配置</a></li>
            {% if permission.global_template %}
            <li class=""><a href="global_template.html">预设模板</a></li>
            {%endif %}
            <li class=""><a href="resource.html">资源管理</a></li>

        </ul>
        <div class="layui-tab-content"></div>
    </div>


    <h1 class="site-h1">应用配置管理 <span style="font-size: 14px;color:red">模板顶层key必须为项目名称!</span></h1>
    {% if permission.template %}
    <button id="create_item" class="layui-btn">新建配置</button>

    {% endif %}

    <table class="layui-hide" id="LAY_table_user" lay-filter="demo"></table>

</div>


<script type="text/html" id="app_global_template_list">

    {{# var app_global_templates = d.global_template }}

    {{#  for( var t in app_global_templates){ }}
    <a class="layui-btn layui-btn-xs" lay-event="app_global_template_{{ t }}">
        {{ t}}</a>
    {{#  } }}

</script>

<script type="text/html" id="template">
    <a class="layui-btn layui-btn-xs" lay-event="template">模板</a>
</script>


<script type="text/html" id="env_config">
    <a class="layui-btn layui-btn-xs" lay-event="env_config_dev">dev</a>
    <a class="layui-btn layui-btn-xs" lay-event="env_config_testenv">testenv</a>

    {% if permission.prod %}<a class="layui-btn layui-btn-xs" lay-event="env_config_prod">prod</a> {% endif %}

</script>

<script type="text/html" id="env">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="dev">dev</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="testenv">testenv</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="prod">prod</a>
</script>


<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs layui-btn-disabled" lay-event="del">删除</a>
</script>


<script src="/asset/layui/layui.js" charset="utf-8"></script>
<script>
    layui.use(['table', "form", "laytpl"], function () {
        var laytpl = layui.laytpl


        var $ = layui.$
        var global_templates = {}

        var editor_value = "";
        var editor_config_value = "";

        var env = "dev"

        function init_global_templates() {
            $.ajax({
                url: "/global_template_list?",
                type: 'GET',
//                contentType: 'text/html',
//                data: JSON.stringify({}),
                success: function (data) {
                    var global_templates1 = data.data
                    for (var ii = 0; ii < global_templates1.length; ii++) {
                        var item = global_templates1[ii]
                        global_templates[item['template_name']] = item['template']
                    }
                },
                error: function (xhr, type) {
                    layer.msg('初始化失败');
                }
            })
        }

        init_global_templates()

        function init_bind(id, el) {
            $(id).on('click', function (event) {
                event.preventDefault();
                try {
                    s = jsyaml.load(el.getValue())
                    console.log(s)

                    layer.alert('YAML验证通过', {
                        icon: 1,
                        skin: 'layer-ext-moon'
                    })

                } catch (err) {
                    console.log(err)
                    layer.alert('YAML验证失败!<br>' + err, {
                        icon: 2,
                        skin: 'layer-ext-moon'
                    })
                }
            });
        }

        init_bind("#btn_validate1", editor_display);
        init_bind("#btn_validate2", editor_config);

        function init_btn_global_template_bind() {
            $(".btn_global_template").on('click', function (event) {
                event.preventDefault();
                var $el = event.currentTarget
                $(".btn_global_template").addClass("layui-btn-primary")
                $($el).removeClass("layui-btn-primary")
                var id = $($el).attr("id")
                env = id.substr("btn_global_template_".length)
                var template_name = $("#global_template").val()
                var app_name = $("#add_global_template_app_name").val()

                set_rendered_global_template(template_name, env, app_name)

            });
        }

        init_btn_global_template_bind()


        var table = layui.table;


        //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            , url: '/config_list'
            , cols: [[

                {field: 'app_name', sort: true, fixed: true, title: "应用名称"},
                {field: 'remark', width: 180, title: "应用描述"},

                {fixed: 'right', width: 300, align: 'center', toolbar: '#env_config', title: "应用环境配置"},
                {fixed: 'right', align: 'center', toolbar: '#barDemo', title: "操作"},


            ]]
            , id: 'testReload'
            , page: true,
            limit: 20,
            limits: [20, 50, 100],

        });

        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj)
        });


        function display_item(data, env) {
            index = layer.open({
                type: 1,
                title: '应用配置',              // [可选]
                content: $('#box_display'),          // 对话框中的内容部分
                area: ['1200px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });
            data['env'] = env
            render_form($("#item_form_display"), data)
            form.render()

            display_rendered_config(data['template'], env, data['app_name'])

        }


        function display_rendered_config(app_template, env, app_name) {

            var template_str = app_template || ""
            var data = {"env": env, "app_name": app_name}
            $.ajax({
                url: "/get_rendered_app_config",
                type: "GET",
                data: data,
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('请求失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false

                    }
                    editor_display.setValue(_data.data)
                    editor_display.gotoLine(1)
                    editor_display.setReadOnly(true)

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

        }

        function edit_config_item(data, env) {
            index = layer.open({
                type: 1,
                title: '应用配置',              // [可选]
                content: $('#box_config'),          // 对话框中的内容部分
                area: ['1200px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });
            data['env'] = env.substr("env_config_".length, env.length)  // env = env_config_xx
            render_form($("#item_form_config"), data)
            form.render()

            console.log(data)
            editor_config.setValue(data[env] || "")
            editor_config.gotoLine(1)
            editor_config_value = data[env] || ""

        }

        //监听工具条
        table.on('tool(demo)', function (obj) {
            if (obj.event === 'del') {
                layer.confirm("确认删除配置", {
                    btn: ['确认', '取消']
                    , btn3: function (index, layero) {

                    }
                }, function (index, layero) {
                    del_item(obj.data)
                    obj.del();

                }, function (index) {

                })
            } else if (obj.event === 'template') {
                edit_item(obj.data)
            } else if (obj.event in {'dev': 1, 'testenv': 1, 'prod': 1,}) {
                display_item(obj.data, obj.event)
            } else if (obj.event in {
                    'env_config_dev': 1,
                    'env_config_testenv': 1,
                    'env_config_beta': 1,

                    'env_config_prod': 1,
                }) {
                edit_config_item(obj.data, obj.event)
            } else if (obj.event === 'add_global_template') {
                add_global_template(obj.data, 0, 0)
            } else if (obj.event.indexOf('app_global_template' >= 0)) {
                app_global_template(obj.data, obj.event)
            }

        });
        function del_item(data) {
            $.ajax({
                url: "/config?app_name=" + data['app_name'],
                type: 'DELETE',
                contentType: 'application/json',
                data: JSON.stringify({}),
                success: function (data) {
                    layer.msg('删除成功');

//                    table.reload('idTest', {});
                    location.reload()
                },
                error: function (xhr, type) {
                    layer.msg('删除失败');
                }
            })
        }

        var index = null

        function set_rendered_global_template(template_name, env, app_name) {

            var template_str = global_templates[template_name] || ""
            var data = {"template": template_str, "env": env, "app_name": app_name}
            $.ajax({
                url: "/render_template",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('请求失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false

                    }
                    editor_add_global_template.setValue(_data.data)
                    editor_add_global_template.gotoLine(1)
                    editor_add_global_template.setReadOnly(true)

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

        }

        function app_global_template(data, event) {
            var option_index = 0
            var template_name = event.substr("app_global_template_".length)
            var ii = 0
            for (var x in global_templates) {
                if (x == template_name) {
                    option_index = ii
                }
                ii += 1
            }
            add_global_template(data, option_index, 1)
        }

        function add_global_template(data, option_index, edit) {
            index = layer.open({
                type: 1,
                title: '添加预设模板',              // [可选]
                content: $('#box_add_global_template'),          // 对话框中的内容部分
                area: ['1200px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });

            $(".btn_global_template").addClass("layui-btn-primary")
            $("#btn_global_template_dev").removeClass("layui-btn-primary")

            $("#global_template").empty()
            var ii = 0
            for (var template_name in global_templates) {
                $("#global_template").append("<option value='" + template_name + "' " + (ii == option_index ? "selected" : "") + " >" + template_name + "</option>")
                if (ii == option_index) {
                    set_rendered_global_template(template_name, "dev", data.app_name)
                }
                ii++
            }

            render_form($("#form_add_global_template"), data)
            form.render()
            $("#add_global_template_app_name").attr("disabled", true)
            $("#add_global_template_app_name").addClass("layui-disabled")

            if (edit) {
                $("#submit_delete").removeClass("hide")
                $("#submit_add").addClass("hide")
            } else {
                $("#submit_add").removeClass("hide")
                $("#submit_delete").addClass("hide")
            }
        }


        function edit_item(data) {
            index = layer.open({
                type: 1,
                title: '编辑模板',              // [可选]
                content: $('#box'),          // 对话框中的内容部分
                area: ['1200px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });
            render_form($("#item-form"), data)
            form.render()
            $("#create_app_name").attr("disabled", true)
            $("#create_app_name").addClass("layui-disabled")

            console.log(data)
        }

        $('#create_item').on('click', function () {
            index = layer.open({
                type: 1,
                title: '新建模板',              // [可选]
                content: $('#box'),          // 对话框中的内容部分
                area: ['1200px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });
            $("#create_app_name").attr("disabled", false)
            $("#create_app_name").removeClass("layui-disabled")

            render_form($("#item-form"))

        });


        var form = layui.form

        //监听提交
        var is_diff = 0
        form.on('submit(demo1)', function (data) {
            if (!is_diff) {
                display_diff(layer, $, editor_value, editor.getValue())
                is_diff = 1
                return false
            }

            is_diff = 0

            delete data.field['_id']
            $.ajax({
                url: "/config",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('提交失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false
                    }
                    layer.msg('更新成功');
                    layer.close(index)
//                    table.reload('idTest', {});
                    location.reload()
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            return false;
        });

        //监听提交
        var is_diff2 = 0
        form.on('submit(demo2)', function (data) {
            if (!is_diff2) {
                display_diff(layer, $, editor_config_value, editor_config.getValue())
                is_diff2 = 1
                return false
            }
            is_diff2 = 0

            var env_config;
            try {
                env_config = editor_config.getValue()
                console.log(env_config)

            } catch (err) {
                console.log(err)
                layer.alert('YAML验证失败!<br>' + err, {
                    icon: 2,
                    skin: 'layer-ext-moon'
                })
                return false
            }
            data.field["env_config"] = env_config;
            $.ajax({
                url: "/app_env_config",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function (_data) {
                    console.log(_data)

                    if (_data.code != 0) {
                        layer.alert('提交失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false

                    }

                    layer.msg('更新成功');
                    layer.close(index)
//                    table.reload('idTest', {});
                    location.reload()
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            return false;
        });


        //监听提交
        form.on('submit(demo3)', function (data) {
            data.field["env_config"] = env_config;
            $.ajax({
                url: "/app_global_template",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('提交失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false

                    }

                    layer.msg('更新成功');
                    layer.close(index)
//                    table.reload('idTest', {});
                    location.reload()
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            return false;
        });


        //监听提交
        form.on('submit(demo4)', function (data) {
            data.field["env_config"] = env_config;
            $.ajax({
                url: "/app_global_template",
                type: "DELETE",
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('提交失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false

                    }

                    layer.msg('更新成功');
                    layer.close(index)
//                    table.reload('idTest', {});
                    location.reload()
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            return false;
        });

        form.on('select(select_global_template)', function (data) {
            console.log(data)
            var app_name = $("#add_global_template_app_name").val()
            set_rendered_global_template(data.value, env, app_name)
            return false
        })

        form.verify({
            yaml: function (value) {
                data = JSON.parse(value)
                if (data == null) {
                    return 'json 不合法';
                }
                return false
            }

        });


    });

    function render_form($form, row) {
        if (!row) {
            $form.find('input').val("");
            $form.find('select').val("");
            $form.find('textarea').val("");
            return
        }
        for (var name in row) {
            $form.find('input[name="' + name + '"]').val(row[name]);
            $form.find('select[name="' + name + '"]').val(row[name]);
            $form.find('textarea[name="' + name + '"]').val(row[name]);
        }

    }
</script>
{% endblock %}
